// dependency from require
var express = require('express');

//create a new instance of Express
// 'app' will be a shortcut when we refer to our application
var app = express();

// configure command is useful for controlling settings that change between environments
app.configure(function() {
	//load the jade library to process jade-based views
	app.set('view engine', 'jade');
	
	//__dirname is one of several global objects available to all
	//modules within Node; it contains the name of the directory that the currently executing
	//script resides in.
	
	//it indicates the root of the application
	app.use(express.static(__dirname + '/public'));
});

// 
app.get('/', function(req, res) {
	res.render("index.jade", {
		layout : false
	});
});

app.get('/account/authenticated', function(req, res) {
	if (req.session.loggedIn) {
		res.send(200);
	} else {
		res.send(401);
	}
});

app.post('/register', function() {
	var firstName = req.param('firstName','');
	var lastName = req.param('lastName','');
	var email = req.param('email', null);
	var password = req.param('password', null);
	
	if (null == email || null == password) {
		res.send(400);
		return;
	}
	
	Account.register(email, password, firstName, lastName);
	res.send(200);
});

app.post('/login', function(req, res) {
	console.log('login request');
	var email = req.param('email', null);
	var password = req.param('password', null);
	
	if (null == email || email.length < 1
			|| null == password || password.length < 1) {
		res.send(400);
		return;
	}
	
	Account.login(email, password, function(success) {
		if (!success) {
			res.send(401);
			return;
		}
		console.log('login successful');
		res.send(200);
	});
});

// port to be listened by the application
app.listen(8080);
console.log("saliendo por 8080");